package com.bluezone.dec.configuration;

import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@EnableSwagger2
@Configuration
public class SwaggerConfiguration {

    @Bean
    public Docket api() {
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        //tokenPar.name("asoco-token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(path -> !Objects.equals(path, "/error"))
                .build()
                //.globalOperationParameters(pars)
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes())
                .apiInfo(this.apiInfo());
    }

    private List<ApiKey> securitySchemes() {
        //WARN Apikey 中name 需和SecurityReference 的reference对应
        ArrayList<ApiKey> apiKeys = Lists.newArrayList(new ApiKey("Authorization","asoco-token" , "header")); return apiKeys;
    }

    private List<SecurityContext> securityContexts() {
        return Lists.newArrayList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        //除Login接口外,都进行验证
                        .forPaths(PathSelectors.regex("^(?!/login).*$"))
                        .build()
        );
    }

    private List<SecurityReference> defaultAuth() {
        return Lists.newArrayList(
                new SecurityReference("Authorization", Lists.newArrayList(
                        new AuthorizationScope("global", "对该范围的接口访问需要使用token")).toArray(new AuthorizationScope[1])));
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("监管决策 后台")
                .description("提供API服务")
                .version("0.0.1")
                .build();
    }
}